import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getMeetingList } from '@/api/meetings'
import { ElMessage } from 'element-plus'

export const useMeetingsStore = defineStore('meetings', () => {
  // 状态
  const meetings = ref([])
  const endedMeetings = ref([]) // 已结束会议列表
  const total = ref(0)
  const endedTotal = ref(0) // 已结束会议总数
  const pageNum = ref(1)
  const pageSize = ref(10)
  const dateRange = ref(['', ''])
  const sortBy = ref('asc')
  const loading = ref(false)
  const searchText = ref('')
  const status = ref('all')

  // 重置筛选条件
  const resetFilters = () => {
    dateRange.value = ['', '']
    sortBy.value = 'asc'
    searchText.value = ''
    status.value = 'all'
    pageNum.value = 1
    pageSize.value = 10
  }

  // 获取会议列表
  const fetchMeetings = async () => {
    loading.value = true
    try {
      const response = await getMeetingList({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        sortType: sortBy.value,
        startDate: dateRange.value[0] || null,
        endDate: dateRange.value[1] || null,
        status: status.value === 'all' ? null : status.value,
        searchText: searchText.value
      })
      
      if (response.code === 200) {
        meetings.value = response.data.items
        total.value = response.data.total
      } else {
        ElMessage.error(response.msg || '获取会议列表失败')
      }
    } catch (error) {
      console.error('获取会议列表错误:', error)
      ElMessage.error('获取会议列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取已结束的会议列表
  const fetchEndedMeetings = async () => {
    loading.value = true
    try {
      const response = await getMeetingList({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        sortType: sortBy.value,
        startDate: dateRange.value[0] || null,
        endDate: dateRange.value[1] || null,
        status: status.value === 'all' ? null : status.value,
        searchText: searchText.value,
        url: '/admins/meetings/getEndedMeetings'
      })
      
      if (response.code === 200) {
        endedMeetings.value = response.data.items
        endedTotal.value = response.data.total
      } else {
        ElMessage.error(response.msg || '获取已结束会议列表失败')
      }
    } catch (error) {
      console.error('获取已结束会议列表错误:', error)
      ElMessage.error('获取已结束会议列表失败')
    } finally {
      loading.value = false
    }
  }

  return {
    meetings,
    endedMeetings,
    total,
    endedTotal,
    pageNum,
    pageSize,
    dateRange,
    sortBy,
    loading,
    searchText,
    status,
    fetchMeetings,
    fetchEndedMeetings,
    resetFilters
  }
})